package model

import (
	"encoding/json"
	"errors"
	"gorm.io/gorm"
	"strings"
	"wwgin/common"
	"wwgin/global/variable"
)

type IpInfo struct {
	gorm.Model `gorm:"-" json:"-"`
	Id         uint   `gorm:"primarykey" json:"id" `
	Ip         uint   `gorm:"unique:true" json:"ip"`
	Country    string `gorm:"size:20" json:"country"`
	Province   string `gorm:"size:10" json:"province"`
	City       string `gorm:"size:10" json:"city"`
	Area       string `gorm:"size:10" json:"area"`
	Isp        string `gorm:"size:10" json:"isp"`
	Other      string `gorm:"size:255" json:"other"`
	AddTime    string `gorm:"default:null" json:"-"`
}

var connect = "def" //使用的数据库

func (i *IpInfo) GetTableName(ip string, ipv6 bool) string {
	var t = "v4"
	var prefix = ip[0:2]

	//检测ip是不是1-9开头的ip
	split := strings.Split(ip, ".")
	if len(split[0]) == 1 {
		prefix = split[0]
	}

	if ipv6 {
		t = "v6"
		prefix = "ipv6"
	}
	return "utf8mb4_ip_info_" + t + "_" + prefix
}

func (i *IpInfo) GetOne(ip string) (IpInfo, error) {
	var ipInfo = IpInfo{}
	toInt := common.InetAtoN(ip)
	find := variable.SqlDB[connect].Table(i.GetTableName(ip, false)).Where("ip = ?", toInt).Find(&ipInfo)
	if find.Error == nil && ipInfo.Id > 0 {
		return ipInfo, nil
	}
	return ipInfo, errors.New("错误没有找到对应的数据")
}

func (i *IpInfo) Add(ip, country, province, city, area, isp, gps, code string) (IpInfo, error) {

	i.Ip = uint(common.InetAtoN(ip))
	i.Country = country
	i.Province = province
	i.City = city
	i.Area = area
	i.Isp = isp

	var other = map[string]string{"gps": gps, "code": code}
	o, _ := json.Marshal(other)
	i.Other = string(o)

	create := variable.SqlDB[connect].Table(i.GetTableName(ip, false)).Create(&i)
	if create.Error == nil && i.Id > 0 {
		return *i, nil
	}
	return *i, create.Error
}
